package main

import (
	"blog-service/global"
	"blog-service/internal/model"
	"blog-service/internal/routers"
	"blog-service/pkg/setting"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"time"
)

func init() {
	err := setupSetting()
	if err != nil {
		log.Fatalf("init.setupSetting err: %v", err)
	}
	err = setupDBEngine()
	if err != nil {
		log.Fatalf("init.setupDBEngine err: %v", err)
	}
}

func main() {
	cfg := global.Settings.Server
	gin.SetMode(cfg.RunMode)
	router := routers.NewRouter()
	s := &http.Server{
		Addr:           ":" + cfg.HttpPort,
		Handler:        router,
		ReadTimeout:    cfg.ReadTimeout,
		WriteTimeout:   cfg.ReadTimeout,
		MaxHeaderBytes: 1 << 20,
	}

	s.ListenAndServe()
}

//初始化配置
func setupSetting() error {
	cfg, err := setting.NewSetting("./configs/config.yaml")
	if err != nil {
		return err
	}
	err = cfg.ReadConf(&global.Settings)
	if err != nil {
		return err
	}
	global.Settings.Server.WriteTimeout *= time.Second
	global.Settings.Server.ReadTimeout *= time.Second
	global.Settings.JWT.Expire *= time.Second
	return nil
}

//初始化mysql
func setupDBEngine() error {
	var err error
	global.DBEngine, err = model.NewDBEngine(global.Settings.Database)
	return err
}
